package cn.edu.fzu.homemaking.sso.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.fzu.homemaking.common.SessionConstant;
import cn.edu.fzu.homemaking.sso.domain.entity.User;
import cn.edu.fzu.homemaking.web.Result;
import cn.edu.fzu.homemaking.web.RetCode;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;

@Order(1)
@WebFilter(urlPatterns = "/api/sso/auth/*")
public class AuthFilter implements Filter {

    @Value("${login.url}")
    private String                    loginUrl;
    @Value("${allow.ip}")
    private String                    allowedIPs;

    private static final List<String> ALLOW_URI = Arrays.asList("/api/sso/auth/user/listAllCompanyUser",
            "/api/sso/auth/user/getNameById");

    @Override
    public void init(FilterConfig filterConfig) {
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        HttpSession session = req.getSession();

        String uri = req.getRequestURI();
        if (ALLOW_URI.contains(uri) && allowedIPs.contains(getIp(req))) {
            chain.doFilter(req, resp);
            return;
        }
        User user = (User) session.getAttribute(SessionConstant.ACCOUNT);
        if (user == null) {
            resp.getWriter().print(JSON.toJSONString(new Result(RetCode.NO_LOGIN, null, null, loginUrl)));
            return;
        }

        chain.doFilter(req, resp);

    }


    @Override
    public void destroy() {
        // do nothing
    }


    private String getIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 获取到多个ip时取第一个作为客户端真实ip
        if (StringUtils.isNotEmpty(ip) && ip.contains(",")) {
            String[] ipArray = ip.split(",");
            if (ArrayUtils.isNotEmpty(ipArray)) {
                ip = ipArray[0];
            }
        }
        return ip;
    }

}
